package com.brkj.course;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.view.ViewGroup;
import android.view.animation.*;
import android.widget.*;
import com.brkj.download.DownLoadCourseActivity;
import com.brkj.download.DownlaodActivity;
import com.brkj.util.Broadcast;
import com.brkj.util.view.BaseActionBarActivity;
import com.brkj.util.view.BaseActionBarItem;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import com.brkj.httpInterface.BaseAjaxParams;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout.LayoutParams;

import com.brkj.model.DS_Course;
import com.brkj.model.DS_CourseClass;
import com.brkj.main.R;
import com.brkj.util.ActivityStackControlUtil;
import com.brkj.httpInterface.HttpInterface.HIF_GetCourse;
import com.brkj.httpInterface.HttpInterface.HIF_GetCourseClass;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.PullListView;
import com.brkj.util.view.PullListView.OnGetMoreListener;
import com.brkj.util.view.PullListView.OnRefreshListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class CourseActivity extends BaseActionBarActivity{

	@ViewInject(id=R.id.courseListView) PullListView courseListView;
	@ViewInject(id=R.id.courseClassView) View courseClassView;
	@ViewInject(id=R.id.allCourse,click="showAllCourse") View allCourse;
	@ViewInject(id=R.id.postCourse,click="showPostCourse") View postCourse;


	private CourseAdapter courseAdapter;

	private PopupWindow popupWindow;
	private GridView gridview;

	public final String COURSE_TYPE_PUBLIC = "0";
	public final String COURSE_TYPE_POST = "1";

	private List<DS_CourseClass> courseClassList_public;
	private List<DS_CourseClass> courseClassList_post;
	
	private CourseClassAdapter courseClassAdapter_public;
	private CourseClassAdapter courseClassAdapter_post;
	
	private Map<Integer, List<DS_Course>> courseListMap_public = new HashMap<Integer,List<DS_Course>>();
	private Map<Integer, List<DS_Course>> courseListMap_post = new HashMap<Integer,List<DS_Course>>();
	private long exitTime;
	
	//默认被选种的分类
	public int selectedClass_public = -1;
	public int selectedClass_post  = 0;

    private ListView courseClassInfoListView;

    private LinearLayout mainView;

    private CourseViewAll courseViewAll;
    private CourseViewClass courseViewClass;
    private CourseViewFavarite courseViewFavarite;
    private CourseViewPush courseViewPush;
    private CourseViewOffline courseViewOffline;
    private View viewAll, viewClass, viewFavarite, viewPush, viewOffline;
    private static FrameLayout parentLayout;

    private BroadcastReceiver br;
    private enum CourseType{
        ALL_COURSE,
        FAVARITE_COURSE,
        CLASS_COURSE,
        PUSH_COURSE,
        OFFLINE_COURSE
    }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.course);

        initTitleBar();

        initBroadCast();
//		initCourseClass();
//		initCourseClassInfo();

		//默认加载岗位课
//		showCourse(COURSE_TYPE_POST, 0, 0);
		
//		courseListView.hideFooterView();

        mainView = (LinearLayout) findViewById(R.id.mainView);
        parentLayout = (FrameLayout) findViewById(R.id.parentLayout);

        courseViewAll = new CourseViewAll(this);
        courseViewClass = new CourseViewClass(this);
        courseViewFavarite = new CourseViewFavarite(this);
        courseViewPush = new CourseViewPush(this);
        courseViewOffline = new CourseViewOffline(this);

        viewAll = courseViewAll.getView();
        viewClass = courseViewClass.getView();
        viewFavarite = courseViewFavarite.getView();
        viewPush = courseViewPush.getView();
        viewOffline = courseViewOffline.getView();

        mainView.addView(viewAll);
        mainView.addView(viewClass);
        mainView.addView(viewFavarite);
        mainView.addView(viewPush);
        mainView.addView(viewOffline);

        showCourseView(CourseType.ALL_COURSE);


	}

    private void initBroadCast() {
        br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                startDownLoadAnim(intent);
            }
        };

        registerReceiver(br, new IntentFilter("com.dgl.startDownloadAnim"));
    }

    private void startDownLoadAnim(Intent intent) {
        final ImageView dlImg = new ImageView(this);
        dlImg.setImageResource(R.drawable.home_list_ico_loading_norm);
        dlImg.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        parentLayout.addView(dlImg);
        AnimationSet animationSet = new AnimationSet(true);

        int[] location = new  int[2] ;
        rightBtnView.getLocationInWindow(location);

        TranslateAnimation anim = new TranslateAnimation(Animation.ABSOLUTE, intent.getIntExtra("xPos", 0),
                Animation.ABSOLUTE, location[0],
                Animation.ABSOLUTE, intent.getIntExtra("yPos", 0),
                Animation.ABSOLUTE, location[1]);

        ScaleAnimation scaleAnim = new ScaleAnimation(1.2f, 0.4f, 1.2f, 0.4f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        RotateAnimation roteAnim = new RotateAnimation(0, 720,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        animationSet.addAnimation(scaleAnim);
        animationSet.addAnimation(roteAnim);
        animationSet.addAnimation(anim);


        animationSet.setDuration(600);

        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                dlImg.setVisibility(View.GONE);

                ScaleAnimation scaleAnim1 = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f);
                scaleAnim1.setDuration(100);
                ScaleAnimation scaleAnim2 = new ScaleAnimation(1.1f, 1.1f, 1.2f, 1.1f);
                scaleAnim2.setDuration(100);

                AnimationSet animationSet = new AnimationSet(true);
                animationSet.addAnimation(scaleAnim1);
                animationSet.addAnimation(scaleAnim2);
                rightBtnView.startAnimation(animationSet);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        dlImg.startAnimation(animationSet);

    }

    private void showCourseView(CourseType courseType) {
        switch(courseType){
            case ALL_COURSE:
                viewAll.setVisibility(View.VISIBLE);
                viewClass.setVisibility(View.GONE);
                viewFavarite.setVisibility(View.GONE);
                viewPush.setVisibility(View.GONE);
                viewOffline.setVisibility(View.GONE);
                courseViewAll.show();
                break;
            case CLASS_COURSE:
                viewAll.setVisibility(View.GONE);
                viewClass.setVisibility(View.VISIBLE);
                viewFavarite.setVisibility(View.GONE);
                viewPush.setVisibility(View.GONE);
                viewOffline.setVisibility(View.GONE);
                courseViewClass.show();
                break;
            case FAVARITE_COURSE:
                viewAll.setVisibility(View.GONE);
                viewClass.setVisibility(View.GONE);
                viewFavarite.setVisibility(View.VISIBLE);
                viewPush.setVisibility(View.GONE);
                viewOffline.setVisibility(View.GONE);
                courseViewFavarite.show();
                break;
            case PUSH_COURSE:
                viewAll.setVisibility(View.GONE);
                viewClass.setVisibility(View.GONE);
                viewFavarite.setVisibility(View.GONE);
                viewPush.setVisibility(View.VISIBLE);
                viewOffline.setVisibility(View.GONE);
                courseViewPush.show();
                break;
            case OFFLINE_COURSE:
                viewAll.setVisibility(View.GONE);
                viewClass.setVisibility(View.GONE);
                viewFavarite.setVisibility(View.GONE);
                viewPush.setVisibility(View.GONE);
                viewOffline.setVisibility(View.VISIBLE);
                courseViewOffline.show();
                break;
            default:
                viewAll.setVisibility(View.VISIBLE);
                viewClass.setVisibility(View.GONE);
                viewFavarite.setVisibility(View.GONE);
                viewPush.setVisibility(View.GONE);
                viewOffline.setVisibility(View.GONE);
                courseViewAll.show();
                break;
        }
    }


//    private void initCourseClassInfo() {
//        courseClassInfoListView  = (ListView) findViewById(R.id.courseClassInfoListView);
//
//    }

    private void initTitleBar() {

        setActivityTitle("课程");
        setSlideMenu();

        rightBtnView = (ImageView)findViewById(R.id.btn_right);
        rightBtnView.setVisibility(View.VISIBLE);
        rightBtnView.setImageResource(R.drawable.title_download_course_selector);
        rightBtnView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CourseActivity.this, DownlaodActivity.class);
                CourseActivity.this.startActivity(intent);
            }
        });

//        addRightButtonItem("学习历史", new BaseActionBarItem.itemClick() {
//            @Override
//            public void onClick() {
//                Intent intent = new Intent(CourseActivity.this, StudyHistoryActivity.class);
//                CourseActivity.this.startActivity(intent);
//            }
//        });

        addTitleButtonItem("全部课程", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {
                showCourseView(CourseType.ALL_COURSE);
            }
        });

        addTitleButtonItem("我的课程", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {

                showCourseView(CourseType.FAVARITE_COURSE);
            }
        });

        addTitleButtonItem("分类课程", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {
                showCourseView(CourseType.CLASS_COURSE);
            }
        });

        addTitleButtonItem("推送课程", new BaseActionBarItem.itemClick() {
            @Override
            public void onClick() {
                showCourseView(CourseType.PUSH_COURSE);
            }
        });

//        addTitleButtonItem("离线课程", new BaseActionBarItem.itemClick() {
//            @Override
//            public void onClick() {
//                showCourseView(CourseType.OFFLINE_COURSE);
//            }
//        });
    }

    public void showCourse(String courseType, int CourseClassID, int CourseID) {
		if(courseType.equals(COURSE_TYPE_PUBLIC)){
			if(courseListMap_public.containsKey(CourseClassID)){
				getView(courseListMap_public.get(CourseClassID), courseType, CourseClassID);
			}else{
				getCourse(courseType, CourseClassID, CourseID);
			}
				
		}else{
			if(courseListMap_post.containsKey(CourseClassID)){
				getView(courseListMap_post.get(CourseClassID), courseType,CourseClassID);
			}else{
				getCourse(courseType, CourseClassID, CourseID);
			}
		}

		
	}

	public void hidePopWindow(){
		popupWindow.dismiss();
	}
	
	public void showAllCourse(View v){
		
		showCourseClassPopUpWindow(COURSE_TYPE_PUBLIC);
	}
	
	public void showPostCourse(View v){
		
		showCourseClassPopUpWindow(COURSE_TYPE_POST);
	}
	
	private void initCourseClass() {
		getCourseClass(COURSE_TYPE_PUBLIC);
		getCourseClass(COURSE_TYPE_POST);
		
		initCourseClassPopUpWindow();
	}

	private void getCourseClass(final String CourseType) {
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetCourseClass.params.CourseType, CourseType);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetCourseClass.address, params, new MyAjaxCallBack<Object>(this) {

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
				if(CourseType.equals(COURSE_TYPE_PUBLIC)){
					
					Gson gson = new Gson();
					Type listType = new TypeToken<List<DS_CourseClass>>(){}.getType();
					courseClassList_public = gson.fromJson((String)t, listType);
					
					if(courseClassList_public != null){
						
						fillCourseClassView(CourseType);
						
					}
				}else if(CourseType.equals(COURSE_TYPE_POST)){
					
					Gson gson = new Gson();
					Type listType = new TypeToken<List<DS_CourseClass>>(){}.getType();
					courseClassList_post = gson.fromJson((String)t, listType);
					
					if(courseClassList_post != null){
						
						fillCourseClassView(CourseType);
						
					}
				}
				
				
			}
			
			
		});
		
	}

	private void fillCourseClassView(String courseType) {
		if(courseType.equals(COURSE_TYPE_PUBLIC)){
			if(courseClassAdapter_public == null){
				courseClassAdapter_public = new CourseClassAdapter(this, courseClassList_public, courseType);
				gridview.setAdapter(courseClassAdapter_public);
			}else{
				courseClassAdapter_public.notifyDataSetInvalidated();
			}
			
		}else{
			if(courseClassAdapter_post == null){
				courseClassAdapter_post = new CourseClassAdapter(this, courseClassList_post, courseType);
				gridview.setAdapter(courseClassAdapter_post);
			}else{
				courseClassAdapter_post.notifyDataSetInvalidated();
			}
		}

		
		
	}

	private void getCourse(final String CourseType, final int CourseClassID, final int CourseID) {
		
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetCourse.params.CourseClass, Integer.toString(CourseClassID));
		params.put(HIF_GetCourse.params.CourseID, Integer.toString(CourseID));
		params.put(HIF_GetCourse.params.CourseType, CourseType);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetCourse.address, params, new MyAjaxCallBack<Object>(this) {

			
			@Override
			public void onFailure(Throwable t, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, strMsg);
				courseListView.onRefreshComplete();
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
//				HIF_GetCourse.result result = JsonUtil.fromJson((String)t, HIF_GetCourse.result.class);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Course>>(){}.getType();
				List<DS_Course> courseList = gson.fromJson((String)t, listType);
				
				if((courseList != null) && (courseList.size() > 0)){
					if(CourseType.equals(COURSE_TYPE_PUBLIC)){
						courseListMap_public.put(CourseClassID, courseList);
						
					}else if(CourseType.equals(COURSE_TYPE_POST)){
						courseListMap_post.put(CourseClassID, courseList);
					}
					
					getView(courseList, CourseType, CourseClassID);
				}else{
					courseListView.setVisibility(View.GONE);
					showToast("此分类暂无课程！");
				}
				
				courseListView.onRefreshComplete();
			}
			
		});
		
	}

	private void getMoreCourse(final String CourseType, final int CourseClassID, final int CourseID) {
		
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetCourse.params.CourseClass, Integer.toString(CourseClassID));
		params.put(HIF_GetCourse.params.CourseID, Integer.toString(CourseID));
		params.put(HIF_GetCourse.params.CourseType, CourseType);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetCourse.address, params, new MyAjaxCallBack<Object>(this) {

			
			@Override
			public void onFailure(Throwable t, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, strMsg);
				courseListView.onGetMoreComplete();
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				
//				HIF_GetCourse.result result = JsonUtil.fromJson((String)t, HIF_GetCourse.result.class);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Course>>(){}.getType();
				List<DS_Course> moreCourseList = gson.fromJson((String)t, listType);
				
				if((moreCourseList != null) && (moreCourseList.size() > 0)){
					if(CourseType.equals(COURSE_TYPE_PUBLIC)){
						if(courseListMap_public.containsKey(CourseClassID)){
							courseListMap_public.get(CourseClassID).addAll(moreCourseList);
							courseAdapter.notifyDataSetChanged();
						}
						
						
					}else if(CourseType.equals(COURSE_TYPE_POST)){
						if(courseListMap_post.containsKey(CourseClassID)){
							courseListMap_post.get(CourseClassID).addAll(moreCourseList);
							courseAdapter.notifyDataSetChanged();
						}
					}
					
				}
				courseListView.onGetMoreComplete();
			}
			
		});
		
	}
	
	private void getView(final List<DS_Course> courseList, final String courseType, final int courseClassID){
		
		courseListView.setVisibility(View.VISIBLE);
		courseAdapter = new CourseAdapter(CourseActivity.this, courseList);
		courseListView.setAdapter(courseAdapter);
		
		courseListView.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				getCourse(courseType, courseClassID, 0);
				
			}
		});
		
		if(courseList.size()>=9){
			courseListView.unHideFooterView();
			courseListView.setonGetMoreListener(new OnGetMoreListener() {
				
				@Override
				public void onGetMore() {
					int courseId = courseList.get(courseList.size()-1).getCourseID();
					getMoreCourse(courseType, courseClassID, courseId);
					
				}
			});
		}else{
			courseListView.hideFooterView();
		}
	}
	
	private void initCourseClassPopUpWindow(){
		
		View popupWindow_view = getLayoutInflater().inflate(
				R.layout.course_class_popupwindow, null, false);
		popupWindow = new PopupWindow(popupWindow_view,
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, false);// 鍒涘缓PopupWindow瀹炰緥

		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// popupWindow.setAnimationStyle(R.style.PopWindowAnim);
		popupWindow.setBackgroundDrawable(new ColorDrawable(0));
		
		gridview = (GridView) popupWindow_view.findViewById(R.id.gridview);
		
		
	}
	
	private void showCourseClassPopUpWindow(String CourseType){
		
		if(CourseType.equals(COURSE_TYPE_PUBLIC)){
			
			if(courseClassList_public == null){
				popupWindow.showAsDropDown(courseClassView);
				getCourseClass(CourseType);
			}else{
				gridview.setAdapter(courseClassAdapter_public);
				popupWindow.showAsDropDown(courseClassView);
			}
			
			
		}else{
			
			if(courseClassList_post == null){
				popupWindow.showAsDropDown(courseClassView);
				getCourseClass(CourseType);
			}else{
				gridview.setAdapter(courseClassAdapter_post);
				popupWindow.showAsDropDown(courseClassView);
			}
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
	        if((System.currentTimeMillis() - exitTime) > 2000){
	            showToast("再按一次退出掌上学苑");
	            exitTime = System.currentTimeMillis();
	        } else {
	        	ActivityStackControlUtil.finishProgram();
	        }
		}
		
		return true;
	}

    @Override
    public void finish() {
        super.finish();
        unregisterReceiver(br);
    }
}
